package com.tigerlee.stopmusic;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Vibrator;
import android.util.Log;

public class WidgetControlReceiver extends BroadcastReceiver{

	private static final String TAG = "WidgetControlBroadcast";
	private MyPreference mPreference;

	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent == null) return;
		Log.e(TAG, intent.getAction());
		mPreference = new MyPreference(context);
		if(StopMusicWidget.INTENT_ACTION_INCREASE_MINS.equals(intent.getAction())){
			int stopAlarm = mPreference.getWidgetTime();
			mPreference.setWidgetTime(stopAlarm + 5);
			updateWidget(context);
		}else if (StopMusicWidget.INTENT_ACTION_DECREASE_MINS.equals(intent.getAction())){
			int stopAlarm = mPreference.getWidgetTime();
			if(stopAlarm > 5) {
				mPreference.setWidgetTime(stopAlarm - 5);
				updateWidget(context);
			}
			
		}else if(UpdateNotificationReceiver.INTENT_ACTION_FINISH_TASK.equals(intent.getAction())){
			updateWidget(context);
		}else if(StopMusicWidget.INTENT_ACTION_TOGGLE_ALARM.equals(intent.getAction())){
			// toggle current state
			mPreference.setRunningState(!mPreference.isRunning());
			if(mPreference.isRunning()){
				int alarmTime = mPreference.getWidgetTime();
				startAlarmService(context, alarmTime, true);
			}else{
				cancelAlarmService(context);
			}
			updateWidget(context);
		}
	}
	public static void updateWidget(Context context) {
		Intent intent = new Intent(context, StopMusicWidget.class);
		intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		int[] ids = manager.getAppWidgetIds(new ComponentName(context, StopMusicWidget.class));
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
		context.sendBroadcast(intent);
	}
	
	public static void startAlarmService(Context context, long alarmTime, boolean fromWidget) {
		Intent intent = new Intent(context, StopMusicService.class);
		PendingIntent pendingIntent = PendingIntent.getService(
				context, 0, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);

		// Get alarm time to start a service at specific time.
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		if(fromWidget){
			alarmTime = System.currentTimeMillis() + alarmTime * 1000 * 60;
		}
		alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
		
		vibrate(context);
		
		// Set running state to preference
		MyPreference preference = new MyPreference(context);
		preference.setRunningState(true);
		if(fromWidget) preference.setTimerState(false);
		preference.setStartTime(System.currentTimeMillis());
		preference.setStopTime(alarmTime);
		// Turn off music by default 
		preference.setTurnOffMusic(true);
		
		// Set repeating time as 30sec to broadcast intent after 1sec
		intent = new Intent(context, UpdateNotificationReceiver.class);
		intent.setAction(UpdateNotificationReceiver.INTENT_ACTION_UPDATE_NOTFICIATION);
		pendingIntent = PendingIntent.getBroadcast(context, 0, 
				intent, PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis() + 1000, 1000 * 15, pendingIntent);
		
		// Start Progress Activity with a flag value
		intent = new Intent(context, StopProgressActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	public static void cancelAlarmService(Context context) {
		Intent intent = new Intent(context, StopMusicService.class);
		PendingIntent pendingIntent = PendingIntent.getService(context, 0,
				intent, PendingIntent.FLAG_CANCEL_CURRENT);

		// Get alarm time to start a service at specific time.
		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		// Request to cancel currently setting alarm
		alarmManager.cancel(pendingIntent);

		// No more updating receiver to create notifications
		intent = new Intent(context, UpdateNotificationReceiver.class);
		intent.setAction(UpdateNotificationReceiver.INTENT_ACTION_UPDATE_NOTFICIATION);
		pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		alarmManager.cancel(pendingIntent);

		// Initialize preference
		new MyPreference(context).initPreference();

		// Broadcast cancel action to interrupt thread progress and stop a
		// notification
		intent = new Intent(context, UpdateNotificationReceiver.class);
		intent.setAction(UpdateNotificationReceiver.INTENT_ACTION_FINISH_TASK);
		context.sendBroadcast(intent);

		// Show stop music activity to reset alarm time...
		intent = new Intent(context, StopMusicActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	public static void vibrate(Context context) {
		// Get instance of AudioManager from current Context
		AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		// Get instance of Vibrator from current Context
		Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
		
		switch (am.getRingerMode()) {
		    case AudioManager.RINGER_MODE_SILENT:
		        Log.d(TAG, "Silent mode - Skip to vibrate");
		        return;
		    case AudioManager.RINGER_MODE_VIBRATE:
		        Log.d(TAG,"Vibrate mode -  vibrate just once");
		        long[] vibrate_pattern = {0, 200};
		        v.vibrate(vibrate_pattern, -1);
		        return;
		    case AudioManager.RINGER_MODE_NORMAL:
		        Log.d(TAG,"Normal mode");
		        break;
		}

		// This example will cause the phone to vibrate "SOS" in Morse Code
		// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
		// There are pauses to separate dots/dashes, letters, and words
		// The following numbers represent millisecond lengths
		int dot = 200; // Length of a Morse Code "dot" in milliseconds
		// int dash = 500; // Length of a Morse Code "dash" in milliseconds
		int short_gap = 200; // Length of Gap Between dots/dashes
		// int medium_gap = 500; // Length of Gap Between Letters
		// int long_gap = 1000; // Length of Gap Between Words
		long[] pattern = { 0, // Start immediately
				dot, short_gap, dot, short_gap, dot, // s
		};

		// Only perform this pattern one time (-1 means "do not repeat")
		v.vibrate(pattern, -1);
	}
}
